package com.shop.test;

import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.shop.dao.ClazzDao;
import com.shop.dao.DeptMapper;
import com.shop.dao.EmpMapper;
import com.shop.entity.Clazz;
import com.shop.entity.Dept;
import com.shop.entity.Emp;
import com.shop.entity.Group;
import com.shop.entity.User;
import com.shop.entity.UserGroupLink;
import com.shop.util.MyBatisUtil;

public class MyBatisTest1 {
	

    private final static String IBATIS_CONFIG_XML  = "mybatis-config.xml";   
    private static SqlSession session;  
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd k:mm:ss");  
            
    @BeforeClass  
    public static void setUpBeforeClass() throws Exception {  
         Reader reader = Resources.getResourceAsReader(IBATIS_CONFIG_XML);  //读取ibatis配置文件  
         SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);  
          session = sqlMapper.openSession(true);  
          session.commit(false); //将默认提交事务属性设置为否  
    }  
      
      
    //保存用户信息  
    @Test  
    public void saveUserTest(){  
        User user = new User();  
        user.setName("张三");  
        user.setPassword("123456");  
        session.insert("com.shop.dao.UserMapper.saveUser", user);  
    }  
     
    //获取用户信息  
    @Test  
    public void getUserTest(){  
        User user = (User) session.selectOne("com.shop.dao.UserMapper.selectUser", 1L);  
        System.out.println("用户名： "+user.getName());  
        System.out.println("用户密码:  "+user.getPassword());  
        System.out.println("用户创建日期："+sdf.format(user.getCreateTime()));  
    }  
     
    //获取用户和用户所在组信息  
    @Test  
    public void getUserAndGroupTest(){  
        User  user =  (User)session.selectOne("com.shop.dao.UserMapper.selectUserGroup", 1L);  
        System.out.println(user.getName() +"所属组信息:");  
        for(Group group : user.getGroups() ){  
            System.out.println("    组名:"+group.getName()+"，组创建时间:"+sdf.format(group.getCreateTime()));  
        }  
    }  
    
    //获取组和组中的用户信息
    @Test
    public void getGroupUser(){
    	Group group = new Group();
    	group.setId(1);
    	Group g = (Group)session.selectOne("com.shop.dao.GroupMapper.selectGroupUser",group);//获取组实例
    	System.out.println(g.getName());
    	System.out.println("该组的用户:");
    	List<User> list =g.getUsers();
    	for (User user : list) {
			System.out.println("\t"+user.getName());
		}
    }
    
    //保存用户和用户所在组信息  当用户所在组不存在时，创建该组，并生成映射关系  
    @Test  
    public void saveUserAndGroupTest(){  
        User user = new User();  
        user.setName("小昭");  
        user.setPassword("383838");  
        session.insert("com.shop.dao.UserMapper.saveUser", user);  //保存用户
          
        Group groupImpl = (Group)session.selectOne("com.shop.dao.GroupMapper.getGroupByName","用户组4");//获取组实例  
        UserGroupLink ugl = new UserGroupLink();//声明User和Group实体间映射关系实例  
          
        //查询到的组实例为空时的逻辑处理  
        if(groupImpl == null){  
             Group group = new Group();  
             group.setName("波斯明教");  
            session.insert("com.shop.dao.GroupMapper.saveGroup", group);//保存组  
              
            //设置映射关系实例相关的属性  
            ugl.setUser(user);  
            ugl.setGroup(group);  
            session.insert("com.shop.dao.UserMapper.saveRelativity",ugl);//保存关系  
                      
        }else{  
            ugl.setGroup(groupImpl);  
            ugl.setUser(user);  
            session.insert("com.shop.dao.UserMapper.saveRelativity",ugl);  
        }  
    }  
      
      
    //删除组信息的同时，取消组内所有的成员与该组的关联关系  
    @Test  
    public void deleteGroupTest(){  
        Group group = new Group();  
        //group.setId(1L);  //以组id作为查询条件  
        group.setName("用户组1"); //以组name作为查询条件  
        Group groupImpl = (Group)session.selectOne("com.shop.dao.GroupMapper.selectGroupUser",group);//获取组实例  
        //组实例存在时  
        if(groupImpl != null){  
            List<User> users = groupImpl.getUsers();  
          //查看用户组1中是否存在用户  
            if(users != null && users.size() > 0){  
                //存在用户时，先删除组与用户的对应关系  
                UserGroupLink ugl = new UserGroupLink();  
                for(User user : users){  
                   ugl.setUser(user);  
                   ugl.setGroup(groupImpl);  
                   session.delete("com.shop.dao.GroupMapper.deleteGroupUser",ugl );  
                }   
            }  
            //删除组信息  
            session.delete("com.shop.dao.GroupMapper.deleteGroup", groupImpl);  
              
        }else{  
            throw new RuntimeException("查询的组不存在!!");  
        }  
          
          
    }  
      
      
    //更新组状态，当组状态由可见状态变成不可见时，取消该组下的用户与该组的映射关系  
    @Test  
    public void updateGroupStateTest(){  
        Group group = new Group();  
        group.setName("用户组2");  
        Group groupImpl = (Group) session.selectOne("com.shop.dao.GroupMapper.selectGroupUser",group);  
          
        if(groupImpl != null){  
            int state = groupImpl.getState() == 1 ? 0 : 1;  
              
              
            //组状态由0变成1时，即由可见变为不可见  
            if(state == 1){  
                List<User> users = groupImpl.getUsers();  
           //查看用户组2中是否存在用户  
                if(users != null && users.size() > 0){  
                      
                    //存在用户时，删除组与用户的对应关系  
                    UserGroupLink ugl = new UserGroupLink();  
                    for(User user : users){  
                       ugl.setUser(user);  
                       ugl.setGroup(groupImpl);  
                       session.delete("com.shop.dao.GroupMapper.deleteGroupUser",ugl );  
                    }   
                }  
            }   
              
            //更新组状态  
            groupImpl.setState(state);  
        }  
        else{  
            throw new RuntimeException("查询的组不存在!!");  
        }  
           
    }  
      
    @AfterClass  
    public static void tearDownAfterClass() throws Exception {  
      if(session != null){  
         session.commit(); //提交事务  
         session.close(); //关闭连接  
      }  
    }   
	
    //一对多级联添加
	@Test 
	public void test3(){
		SqlSession session  =MyBatisUtil.getSqlSession();
		DeptMapper deptMapper = session.getMapper(DeptMapper.class);
		EmpMapper empMapper  =session.getMapper(EmpMapper.class);
		Dept dept =new Dept(null, "西游记", "大雷音寺");
		List<Emp> list = Arrays.asList(
				new Emp(null, "唐僧", new Date(), "师傅", 1000, null),
				new Emp(null, "孙悟空", new Date(), "大师兄", 800, null),
				new Emp(null, "猪八戒", new Date(), "二师兄", 600, null),
				new Emp(null, "沙悟净", new Date(), "沙师弟", 300, null)
				);
		dept.setEmps(list);
		deptMapper.saveDept(dept);
		session.commit();//先提交事务
		
		for (Emp emp :dept.getEmps()) {
			emp.setDeptNo(dept.getDeptNo());
			empMapper.saveEmp(emp);
		}
		session.commit();
		session.close();
	}
    
	
	@Test 
	public void test2(){
		SqlSession session  =MyBatisUtil.getSqlSession();
		DeptMapper mapper = session.getMapper(DeptMapper.class);
		Dept dept = mapper.getDept(1);
		System.out.println("部门名称:"+dept.getDname()+",地址:"+dept.getLoc());
		System.out.println("包含的员工信息:");
		for (Emp emp :dept.getEmps()) {
			System.out.println(emp);
		}
		session.close();
	}
	
	
	@Test
	public void test1(){
		SqlSession session  =MyBatisUtil.getSqlSession();
		ClazzDao clazzDao = session.getMapper(ClazzDao.class);
		Clazz class1 = clazzDao.getClass(1);
		System.out.println(class1);
		MyBatisUtil.closesSession(session);
	}
	
}
